﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.FileTransferService;
using FileManager_Client.PresentationLayer.NewUi;
using FileManager_Client.PresentationLayer.Properties;
using FileManager_Client.Utility;
using System.Linq;

namespace FileManager_Client.PresentationLayer
{
    public partial class ServerFiles : Form
    {
        #region Constructor 
        private CompanyResultCollection companyCollection;
        private FolderResultCollection folderCollection;
        private FolderRoleResultCollection folderRoleCollection;
        private TreeNode selectNode;
        private UserLoginResult userSession;
        private WaitDialogForm _waitBeforeLogin;
        private FileService fileService;
        private static object _lockObj = new object();
        private UploadTask uploadTask;
        private DownloadTask donDownloadTask;
        public ServerFiles()
        {
            InitializeComponent();
            fileService = new FileService();
            var size = new Size(SystemInformation.WorkingArea.Width - 5, SystemInformation.WorkingArea.Height - 5);
            CacheGlobal.Add(GlobalString.System_Config_String.Wcf_FileTransferServiceCacheKey,new FileTransfer_ServiceClient());
            var t1 = size - MaximumSize;
            var r2 = size - MinimumSize;
            lvFileView.MaximumSize += t1;
            lvFileView.MinimumSize += t1;
            this.MaximumSize = size;
            this.MinimumSize = size;
            tvFileView.ExpandAll();
            this.skinEngine1.SkinFile = "office2007.ssk";
            this.StartPosition = FormStartPosition.CenterScreen;
            InitData();
            tvFileView.NodeMouseClick += tvFileView_NodeMouseClick;
            tvFileView.AfterSelect += tvFileView_AfterSelect;
            lvFileView.ColumnClick += lvFileView_ColumnClick;
            lvFileView.MouseDoubleClick += lvFileView_MouseDoubleClick;
            lvFileView.MouseClick += lvFileView_MouseClick;
        }

        public void InitData()
        {
            companyCollection =
    CacheGlobal.GetCache(GlobalString.System_Config_String.CompanyCollectionCache) as
    CompanyResultCollection ??
    new CompanyResultCollection { CompanyResultsk__BackingField = new CompanyResult[0] };
            folderCollection =
                CacheGlobal.GetCache(GlobalString.System_Config_String.FolderCollectionCache) as
                FolderResultCollection ??
                new FolderResultCollection { FolderCollectionk__BackingField = new FolderResult[0] };
            folderRoleCollection =
                CacheGlobal.GetCache(GlobalString.System_Config_String.FolderRoleCollectionCache) as
                FolderRoleResultCollection ??
                new FolderRoleResultCollection { RoleResultsk__BackingField = new FolderRoleResult[0] };
            userSession =
                CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult
                ?? new UserLoginResult();
            lvFileView.Items.Clear();
            tvFileView.Nodes.Clear();
            var rootNodeData =
                companyCollection.CompanyResultsk__BackingField.FirstOrDefault(x => x.Pidk__BackingField.Equals("0"));
            var rootNode = new TreeNode
            {
                Text = rootNodeData.ShortNamek__BackingField,
                ImageKey = GlobalString.System_Image_String.CompanyImageKey,
                Tag = rootNodeData,
                ContextMenuStrip = cms_NoRole,
                Name = rootNodeData.Idk__BackingField
            };
            rootNode.Expand();
            tvFileView.Nodes.Add(rootNode);
            var subNodeData =
                companyCollection.CompanyResultsk__BackingField.Where(
                    x => x.Pidk__BackingField.Equals(rootNodeData.Idk__BackingField)).ToList();
            foreach (var subNode in subNodeData.Select(companyResult => new TreeNode
            {
                Text = companyResult.ShortNamek__BackingField,
                ImageKey = GlobalString.System_Image_String.CompanyImageKey,
                Tag = companyResult,
                ContextMenuStrip = userSession.CompanyIdk__BackingField.Equals(companyResult.Idk__BackingField) ? cms_MyCompanyRootRole : cms_NoRole,
                Name = companyResult.Idk__BackingField
            }))
            {
                rootNode.Nodes.Add(subNode);
            }
            //FIND ROOT SUBFOLDER
            var rootFolder =
                folderCollection.FolderCollectionk__BackingField.Where(x => x.ParentIdk__BackingField.Equals("0")).
                    ToList();
            foreach (var folderInfo in rootFolder)
            {
                var contextMenuStrip = folderInfo.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField)
                    || folderInfo.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField) ? cms_myComapnyFolderRole : cms_OtherComapnyFolderRole;
                var currentNode = tvFileView.Nodes.Find(folderInfo.OwnerIdk__BackingField, true);
                if (currentNode.Length <= 0) continue;
                var currentRoot = currentNode[0];
                var subFolderNode = new TreeNode
                {
                    Text = folderInfo.FileNamek__BackingField,
                    ImageKey = GlobalString.System_Image_String.FolderImageKey,
                    Tag = new NodeArgs { FolderResult = folderInfo },
                    ContextMenuStrip = contextMenuStrip,
                    Name = folderInfo.FileSidk__BackingField,
                    SelectedImageKey = GlobalString.System_Image_String.FolderOpenImageKey,
                };
                var currentSubFolderNodes = ReturnTreeNode(folderInfo.FileSidk__BackingField, contextMenuStrip);
                foreach (var currentSubFolderNode in currentSubFolderNodes)
                    subFolderNode.Nodes.Add(currentSubFolderNode);
                currentRoot.Nodes.Add(subFolderNode);
            }
            foreach (var folderRole in folderRoleCollection.RoleResultsk__BackingField)
            {
                var node = tvFileView.Nodes.Find(folderRole.FileIdk__BackingField, true);
                if (!node.Any()) continue;
                var objArgs = node[0].Tag as NodeArgs;
                if (null == objArgs) continue;
                objArgs.FolderRoleResult = folderRole;
                node[0].Tag = objArgs;
            }
            tvFileView.Update();
        }
        private IEnumerable<TreeNode> ReturnTreeNode(string parentId, ContextMenuStrip contextMenuStrip)
        {
            var result = new List<TreeNode>();
            var subFolders =
                folderCollection.FolderCollectionk__BackingField.Where(x => x.ParentIdk__BackingField.Equals(parentId)).
                    ToList();
            foreach (var folderResult in subFolders)
            {
                var subFolderNode = new TreeNode
                {
                    Text = folderResult.FileNamek__BackingField,
                    ImageKey = GlobalString.System_Image_String.FolderImageKey,
                    Tag = new NodeArgs { FolderResult = folderResult },
                    ContextMenuStrip = contextMenuStrip,
                    Name = folderResult.FileSidk__BackingField,
                    SelectedImageKey = GlobalString.System_Image_String.FolderOpenImageKey
                };
                var subsubNodes = ReturnTreeNode(folderResult.FileSidk__BackingField, contextMenuStrip);
                foreach (var subsubNode in subsubNodes)
                    subFolderNode.Nodes.Add(subsubNode);
                result.Add(subFolderNode);
            }
            return result;
        }
        #endregion

        #region TreeView event
        void tvFileView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (null != selectNode)
                selectNode.BackColor = Color.Transparent;
            selectNode = e.Node;
            selectNode.BackColor = Color.Blue;
            var tagObj = selectNode.Tag as NodeArgs;
            SetPbImage(tagObj);
            lvFileView.Items.Clear();
            if (null == tagObj) return;
            var fileQueryArgs = new FileQueryArgs
                                    {
                                        FolderIdk__BackingField = tagObj.FolderResult.FileSidk__BackingField,
                                        UserIdk__BackingField = userSession.UserIdk__BackingField
                                    };
            if(tagObj.FolderResult.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField))
                fileQueryArgs.IsJustMek__BackingField = false;
            else
            {
                if (null == tagObj.FolderRoleResult) return;
                    var checkPermission = tagObj.FolderRoleResult.IsCreatek__BackingField | tagObj.FolderRoleResult.IsDeletek__BackingField
                          | tagObj.FolderRoleResult.IsUpdatek__BackingField | tagObj.FolderRoleResult.IsReadk__BackingField;
                    if (checkPermission)
                        fileQueryArgs.IsJustMek__BackingField = false;
                    else
                        return;
                    fileQueryArgs.IsJustMek__BackingField = tagObj.FolderRoleResult.IsJustMek__BackingField;
            }
            var backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            //
            backgroundWorker.RunWorkerAsync(fileQueryArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.GetFolderFileCollectionLoadingStr, GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
               // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
                _waitBeforeLogin.ShowDialog();
            }
        }

        private void tvFileView_NodeMouseClick_1(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right) tvFileView.SelectedNode = e.Node;
        }

        void tvFileView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //if (e.Button == MouseButtons.Right) tvFileView.SelectedNode = e.Node;
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var result = e.Result as FileResultCollection;
            if(null != result)
            {
                foreach (var file in result.FileCollectionk__BackingField)
                {
                    var lvItem = new ListViewItem
                                     {
                                         Text = file.FileNamek__BackingField,
                                         ImageKey = ReturnImageKey(file.FileNamek__BackingField),
                                         Tag = file,
                                         Name = file.FileSidk__BackingField
                                     };
                    var lvSubItem0 = new ListViewItem.ListViewSubItem
                                         {Text = file.CreateTimek__BackingField.ToShortDateString()};
                    var lvSubItem1 = new ListViewItem.ListViewSubItem {Text = file.CreateNamek__BackingField};
                    var lvSubItem2 = new ListViewItem.ListViewSubItem
                                         {Text = file.UpdateTimek__BackingField.ToShortDateString()};
                    var lvSubItem3 = new ListViewItem.ListViewSubItem {Text = file.UpdateNamek__BackingField};
                    var lvSubItem4 = new ListViewItem.ListViewSubItem {Text = file.FileSizek__BackingField + "kb"};
                    var lvSubItem5 = new ListViewItem.ListViewSubItem {Text = "文件"};
                    lvItem.SubItems.Add(lvSubItem0);
                    lvItem.SubItems.Add(lvSubItem1);
                    lvItem.SubItems.Add(lvSubItem2);
                    lvItem.SubItems.Add(lvSubItem3);
                    lvItem.SubItems.Add(lvSubItem4);
                    lvItem.SubItems.Add(lvSubItem5);
                    
                    lvFileView.Items.Add(lvItem);
                }
                var node = tvFileView.SelectedNode;
                var childNodes = node.Nodes;
                foreach (TreeNode childNode in childNodes)
                {
                    var nodeArgs = childNode.Tag as NodeArgs;
                    if (null == nodeArgs) continue;
                    var lvItem = new ListViewItem
                    {
                        Text = nodeArgs.FolderResult.FileNamek__BackingField,
                        ImageKey = GlobalString.System_Image_String.FolderPngImageKey,
                        Tag = nodeArgs,
                        Name = nodeArgs.FolderResult.FileSidk__BackingField
                    };
                    var lvSubItem0 = new ListViewItem.ListViewSubItem { Text = string.IsNullOrEmpty(nodeArgs.FolderResult.CreateTimek__BackingField) ? "" : DateTime.Parse(nodeArgs.FolderResult.CreateTimek__BackingField).ToShortDateString() };
                    var lvSubItem1 = new ListViewItem.ListViewSubItem { Text = nodeArgs.FolderResult.CreateNamek__BackingField };
                    var lvSubItem2 = new ListViewItem.ListViewSubItem { Text = string.IsNullOrEmpty(nodeArgs.FolderResult.UpdateTimek__BackingField)?"":DateTime.Parse(nodeArgs.FolderResult.UpdateTimek__BackingField).ToShortDateString() };
                    var lvSubItem3 = new ListViewItem.ListViewSubItem { Text = nodeArgs.FolderResult.UpdateNamek__BackingField };
                    var lvSubItem4 = new ListViewItem.ListViewSubItem { Text = "" };
                    var lvSubItem5 = new ListViewItem.ListViewSubItem { Text = "文件夹" };
                    lvItem.SubItems.Add(lvSubItem0);
                    lvItem.SubItems.Add(lvSubItem1);
                    lvItem.SubItems.Add(lvSubItem2);
                    lvItem.SubItems.Add(lvSubItem3);
                    lvItem.SubItems.Add(lvSubItem4);
                    lvItem.SubItems.Add(lvSubItem5);
                    lvFileView.Items.Add(lvItem);
                }
            }
            lock (_lockObj)
            {
                _waitBeforeLogin.Close();
            }
        }

        private string ReturnImageKey(string fileName)
        {
            var result = string.Empty;
            var fileExtension = Path.GetExtension(fileName).ToLower();
            switch (fileExtension)
            {
                case ".docx":
                case ".doc":
                    result = GlobalString.System_Image_String.WordImageKey;
                    break;
                case ".txt":
                    result = GlobalString.System_Image_String.TxtImageKey;
                    break;
                case ".xlsx":
                case ".xls":
                    result = GlobalString.System_Image_String.ExcelImageKey;
                    break;
                case ".pptx":
                case ".ppt":
                    result = GlobalString.System_Image_String.PptImageKey;
                    break;
                case ".accdb":
                    result = GlobalString.System_Image_String.AccessImageKey;
                    break;
                case ".zip":
                    result = GlobalString.System_Image_String.ZipImageKey;
                    break;
                case ".rar":
                    result = GlobalString.System_Image_String.RarImageKey;
                    break;
                case ".pdf":
                    result = GlobalString.System_Image_String.PdfImageKey;
                    break;
                case ".jpg":
                case ".jpeg":
                    result = GlobalString.System_Image_String.JpgImageKey;
                    break;
                case ".png":
                    result = GlobalString.System_Image_String.PngImageKey;
                    break;
                case ".gif":
                    result = GlobalString.System_Image_String.GifImageKey;
                    break;
                case ".bmp":
                    result = GlobalString.System_Image_String.BmpImageKey;
                    break;
                case ".exe":
                    result = GlobalString.System_Image_String.ExeImageKey;
                    break;
                case ".htm":
                case ".html":
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
                case ".xml":
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
                case ".mp3":
                    result = GlobalString.System_Image_String.Mp3ImageKey;
                    break;
                case ".wav":
                    result = GlobalString.System_Image_String.WmaImageKey;
                    break;
                case ".avi":
                    result = GlobalString.System_Image_String.AviImageKey;
                    break;
                case ".bat":
                    result = GlobalString.System_Image_String.BatImageKey;
                    break;
                default:
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
            }
            return result;
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = fileService.GetFolderFileCollection(e.Argument as FileQueryArgs);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.GetFolderFileCollectionExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }

        public void UpdateListView(string folderId)
        {
            var nodeTag = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null != tvFileView.SelectedNode && null != nodeTag&&nodeTag.FolderResult.FileSidk__BackingField.Equals(folderId))
                    tvFileView_AfterSelect(tvFileView, new TreeViewEventArgs(tvFileView.SelectedNode));
            else
            {
                var node = tvFileView.Nodes.Find(folderId, true);
                if (node.Length > 0)
                {
                    node[0].ExpandAll();
                    tvFileView.SelectedNode = node[0];
                   // tvFileView_AfterSelect(tvFileView, new TreeViewEventArgs(node[0]));
                }
                    
            }
        }

        #endregion

        #region Root company and sub other company root role context menu event
        /// <summary>
        /// Root company and other company root haven't context menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_NoRole_Opening(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
        #endregion

        #region Other company folder context menu evnet
        /// <summary>
        /// Folder log
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_Log_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> { tvFileView.SelectedNode.Name };
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogs(fileSidCollection);
            fileLogs.ShowDialog();
        }
        /// <summary>
        /// Folder role copy to
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_OtherComapnyRoleCopyTo_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            if(null == obj.FolderRoleResult && !obj.FolderResult.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField))
            {
                XtraMessageBox.Show(GlobalString.System_Config_String.FolderHaventRoleStr,
                                    GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
            }
            else
            {
                var rightsManageMent = new RightsManagement(obj.FolderResult.FileSidk__BackingField, obj, true);
                rightsManageMent.ShowDialog();
            }
        }
        /// <summary>
        /// Check other company folder role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_OtherComapnyFolderRole_Opening(object sender, CancelEventArgs e)
        {

        }
        #endregion

        #region My company root context menu event
        /// <summary>
        /// Create new folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            var parentId = string.Empty;
            parentId = null == nodeArgs ? (tvFileView.SelectedNode.Tag as CompanyResult).Idk__BackingField : nodeArgs.FolderResult.FileSidk__BackingField;
            var hasFolderName = (from TreeNode node in tvFileView.SelectedNode.Nodes select node.Text).ToList();
            var af = new AddFile(hasFolderName, parentId, this);
            af.ShowDialog();
            InitData();
            UpdateListView(parentId);
        }
        /// <summary>
        /// Query root log
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> { tvFileView.SelectedNode.Name };
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogs(fileSidCollection);
            fileLogs.ShowDialog();
        }
        #endregion

        #region My company folder context menu event
        /// <summary>
        /// Create new folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            var parentId = string.Empty;
            parentId = null == nodeArgs ? (tvFileView.SelectedNode.Tag as CompanyResult).Idk__BackingField : nodeArgs.FolderResult.FileSidk__BackingField;
            var hasFolderName = (from TreeNode node in tvFileView.SelectedNode.Nodes select node.Text).ToList();
            var af = new AddFile(hasFolderName, parentId, this);
            af.ShowDialog();
            InitData();
            UpdateListView(parentId);
        }
        /// <summary>
        /// Delete folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var delItem = tvFileView.SelectedNode.Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFolderMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var folderDeleteArgs = new FolderDeleteArgs
            {
                FolderSidk__BackingField =
                    (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult.FileSidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            var backgroundWokerDeleteFolder = new BackgroundWorker();
            backgroundWokerDeleteFolder.DoWork += backgroundWokerDeleteFolder_DoWork;
            backgroundWokerDeleteFolder.RunWorkerCompleted += backgroundWokerDeleteFolder_RunWorkerCompleted;
            backgroundWokerDeleteFolder.RunWorkerAsync(folderDeleteArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.DeleteingFolderStr, GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
                _waitBeforeLogin.ShowDialog();
            }
        }
        /// <summary>
        /// Rename folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_MyCompanyFolderRename_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var folderNameColletion = (from TreeNode c in tvFileView.SelectedNode.Parent.Nodes select c.Text).ToList();
            var currentFolderName = tvFileView.SelectedNode.Text;
            folderNameColletion.Remove(currentFolderName);
            var reNameFolderForm = new ReNameFolder(folderNameColletion, currentFolder.FolderResult.FileSidk__BackingField, currentFolderName, this);
            reNameFolderForm.ShowDialog();
        }
        /// <summary>
        /// Query folder log
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_MyCompanyFolderLogQuery_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> {tvFileView.SelectedNode.Name};
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogs(fileSidCollection);
            fileLogs.ShowDialog();
        }
        /// <summary>
        /// Copy folder to
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 复制到ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if(null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FolderCopy, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        /// <summary>
        /// Cut folder to
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 剪切到ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FolderCut, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }
        /// <summary>
        /// Folder role manage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 权限管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            var folderSid = (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult.FileSidk__BackingField;
            var rm = new RightsManagement(folderSid,null);
            rm.ShowDialog();
        }
        #endregion

        #region ListView event
        private void 大图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.lvFileView.View = View.LargeIcon;
        }

        private void 小图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.lvFileView.View = View.SmallIcon;
        }

        private void 列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.lvFileView.View = View.Details;           
        }

        void lvFileView_MouseClick(object sender, MouseEventArgs e)
        {
          if(e.Button == MouseButtons.Right)
          {
              var hit = lvFileView.HitTest(e.Location);
              if (hit.Item != null)
              {
                  var args = hit.Item.Tag as FileResult;
                  lvFileView.ContextMenuStrip = null == args ? cms_FolderRightMenu : cms_FileRightMenu;
              }
             // else
                //  lvFileView.ContextMenuStrip = contextMenuStrip1;
              lvFileView.ContextMenuStrip.Show();
          }
        }

        void lvFileView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) return;
            //  if(lvFileView.SelectedItems.Count == 1)
            var hit = lvFileView.HitTest(e.Location);
            if (hit.Item != null)
            {
                var args = hit.Item.Tag as FileResult;
                if (null == args)
                {
                    var folderArgs = hit.Item.Tag as NodeArgs;
                    var nodes = tvFileView.Nodes.Find(folderArgs.FolderResult.FileSidk__BackingField, true);
                    if (nodes.Count() == 1)
                        tvFileView.SelectedNode = nodes[0];
                }
                else
                {
                    var fileArgs = hit.Item.Tag as FileResult;
                    var autoSavePath = Path.GetTempPath();
                    autoSavePath += fileArgs.FileNamek__BackingField;
                    donDownloadTask = new DownloadTask(fileArgs, tsslDownLoadTask, this, autoSavePath,true);
                    donDownloadTask.ShowDialog();
                    donDownloadTask = null;
                    // donDownloadTask = new DownloadTask(); UploadTask(dlg.FileNames, nodeArgs.FolderResult, tsslUploadTask);
                    //      uploadTask.ShowDialog();
                }
            }
        }
        void lvFileView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            lvFileView.ListViewItemSorter = new ListViewItemComparer(e.Column);
            lvFileView.Sort();
        }

        private void tsmi_OpenFolder_Click(object sender, EventArgs e)
        {
            var args = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null != args) return;
            var folderArgs = lvFileView.SelectedItems[0].Tag as NodeArgs;
            var nodes = tvFileView.Nodes.Find(folderArgs.FolderResult.FileSidk__BackingField, true);
            if (nodes.Count() == 1)
                tvFileView.SelectedNode = nodes[0];
        }


        private void lvFileView_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None;
        }

        private void lvFileView_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                var files = e.Data.GetData(DataFormats.FileDrop, false) as String[];
                // Copy file from external application 
                foreach (string srcfile in files)
                {
                    var destFile = Path.GetFileName(srcfile);

                    File.Copy(srcfile, destFile, true);
                }
                // List current folder 
             //   ListFolder();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, " Error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } 
        }
        /// <summary>
        /// ContextMenu click download
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmsi_DownloadFile_Click(object sender, EventArgs e)
        {
            if(lvFileView.SelectedItems.Count == 1)
            {
                var listViewItem = lvFileView.SelectedItems[0];
                var fileResult = listViewItem.Tag as FileResult;
                var saveFileDialog = new SaveFileDialog {FileName = fileResult.FileNamek__BackingField};
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    donDownloadTask = new DownloadTask(fileResult, tsslDownLoadTask, this, saveFileDialog.FileName);
                    donDownloadTask.ShowDialog();
                }
            }
        }

        #endregion

        #region Current from event
        private void ServerFiles_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }
        #endregion

        #region Public method
        private void SetPbImage(NodeArgs tagObj)
        {
            foreach (ToolStripItem item in cms_MyCompanyRootRole.Items)
                item.Enabled = true;
            foreach (ToolStripItem item in cms_FolderRightMenu.Items)
                item.Enabled = true;
            foreach (ToolStripItem item in cms_FileRightMenu.Items)
                item.Enabled = true;
            if (null == tagObj)
            {

                pbSubmitFalse.Image = Resources.baosong_disable;
                pbSubmitFalse.Cursor = Cursors.No;
                pbEditTrue.Image = Resources.edit_disable;
                pbEditTrue.Cursor = Cursors.No;
                pbDownloadFalse.Image = Resources.download_disable;
                pbDownloadFalse.Cursor = Cursors.No;
                pbDeleteFalse.Image = Resources.delete_disable;
                pbDeleteFalse.Cursor = Cursors.No;
                pbCreateTrue.Image = Resources.create_disable;
                pbCreateTrue.Cursor = Cursors.No;
            }
            else
            {
                if (tagObj.FolderResult.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField)
                    || tagObj.FolderResult.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField))
                {
                    if (tagObj.FolderRoleResult == null)
                        tagObj.FolderRoleResult = new FolderRoleResult();
                    tagObj.FolderRoleResult.IsCreatek__BackingField = true;
                    tagObj.FolderRoleResult.IsDeletek__BackingField = true;
                    tagObj.FolderRoleResult.IsJustMek__BackingField = true;
                    tagObj.FolderRoleResult.IsReadk__BackingField = true;
                    tagObj.FolderRoleResult.IsUpdatek__BackingField = true;
                }
                else
                {
                    if (tagObj.FolderRoleResult == null)
                        tagObj.FolderRoleResult = new FolderRoleResult();
                    tagObj.FolderRoleResult.IsCreatek__BackingField = false;
                    tagObj.FolderRoleResult.IsDeletek__BackingField = false;
                    tagObj.FolderRoleResult.IsJustMek__BackingField = false;
                    tagObj.FolderRoleResult.IsReadk__BackingField = false;
                    tagObj.FolderRoleResult.IsUpdatek__BackingField = false;
                }
                pbSubmitFalse.Image = tagObj.FolderRoleResult.IsJustMek__BackingField
                                          ? Resources.permission_baosong
                                          : Resources.baosong_disable;
                pbSubmitFalse.Cursor = tagObj.FolderRoleResult.IsJustMek__BackingField
                                           ? Cursors.Arrow
                                           : Cursors.No;
                pbEditTrue.Image = tagObj.FolderRoleResult.IsUpdatek__BackingField
                                       ? Resources.permission_edit
                                       : Resources.edit_disable;
                pbEditTrue.Cursor = tagObj.FolderRoleResult.IsUpdatek__BackingField
                                        ? Cursors.Arrow
                                        : Cursors.No;
                pbDownloadFalse.Image = tagObj.FolderRoleResult.IsReadk__BackingField
                                            ? Resources.permission_download
                                            : Resources.download_disable;
                pbDownloadFalse.Cursor = tagObj.FolderRoleResult.IsReadk__BackingField
                                             ? Cursors.Arrow
                                             : Cursors.No;
                pbDeleteFalse.Image = tagObj.FolderRoleResult.IsDeletek__BackingField
                                          ? Resources.permission_delete
                                          : Resources.delete_disable;
                pbDeleteFalse.Cursor = tagObj.FolderRoleResult.IsDeletek__BackingField
                                           ? Cursors.Arrow
                                           : Cursors.No;
                pbCreateTrue.Image = tagObj.FolderRoleResult.IsCreatek__BackingField
                                         ? Resources.permission_create
                                         : Resources.create_disable;
                pbCreateTrue.Cursor = tagObj.FolderRoleResult.IsCreatek__BackingField
                                          ? Cursors.Arrow
                                          : Cursors.No;
            }
            cms_FileRightMenu.Items["tsmi_RenameFile"].Enabled = pbEditTrue.Cursor == Cursors.Arrow;
            cms_FolderRightMenu.Items["tsmi_RenameFolder"].Enabled = pbEditTrue.Cursor == Cursors.Arrow;
            cms_FileRightMenu.Items["tmsi_DownloadFile"].Enabled = pbDownloadFalse.Cursor == Cursors.Arrow;
            cms_FileRightMenu.Items["tsmi_DeleteFile"].Enabled = pbDeleteFalse.Cursor == Cursors.Arrow;
            cms_FolderRightMenu.Items["tsmi_DeleteFolder"].Enabled = pbDeleteFalse.Cursor == Cursors.Arrow;
            //
        }

        public void UpdateFolderName(string folderSid,string folderNewName)
        {
            var nodeCollection = tvFileView.Nodes.Find(folderSid, true);
            if(nodeCollection.Length == 1)
                nodeCollection[0].Text = folderNewName;
            var itemCollection = lvFileView.Items.Find(folderSid,false);
            if(itemCollection.Length == 1)
                itemCollection[0].Text = folderNewName;
        }
        #endregion

        void treeView2_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Nodes.Count > 0)
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.Collapse();

                }
                else
                {
                    e.Node.Expand();
                }
            }
            else
            {
                if (Directory.Exists(e.Node.Name))
                {
                    try
                    {
                        string[] allDirectory = Directory.GetDirectories(e.Node.Name);
                        foreach (string s in allDirectory)
                        {
                            e.Node.Nodes.Add(s, s.Remove(0, s.LastIndexOf("//") + 1));
                        }
                        //listBox1.Items.Clear();
                        string[] allFiles = Directory.GetFiles(e.Node.Name);
                        foreach (string sf in allFiles)
                        {
                            //listBox1.Items.Add(sf.Remove(0, sf.LastIndexOf("//") + 1));
                        }
                    }
                    catch
                    {
                    }
                }
                e.Node.Expand();
            }
        }


        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }

            else
            {
                e.Effect = DragDropEffects.None;
            }

        }


        /// <summary>
        /// 上传本地文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            if (pbSubmitFalse.Cursor == Cursors.No && pbEditTrue.Cursor == Cursors.No&& pbDeleteFalse.Cursor == Cursors.No
                && pbCreateTrue.Cursor == Cursors.No)
                return;
            var dlg = new OpenFileDialog {Multiselect = true, RestoreDirectory = true}; //创建一个OpenFileDialog  
            if (dlg.ShowDialog() != DialogResult.OK) return;
            if (dlg.FileNames == null || !dlg.FileNames.Any()) return;
            var message = string.Format(GlobalString.System_Config_String.UploadFileMessageBox,
                                        dlg.FileNames.Count());
            XtraMessageBox.AllowCustomLookAndFeel = true;
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            uploadTask = new UploadTask(dlg.FileNames, nodeArgs.FolderResult, tsslUploadTask,this);
            uploadTask.ShowDialog();
            uploadTask = null;
        }

        private void pictureBox16_Click(object sender, EventArgs e)
        {
            var fs = new FileSerch(this);
            fs.Closed += fs_Closed;
            fs.ShowDialog();
        }

        void fs_Closed(object sender, EventArgs e)
        {
            
        }

        private void toolStripStatusLabel2_Click(object sender, EventArgs e)
        {
            if (null != donDownloadTask && !donDownloadTask.IsDisposed)
                donDownloadTask.ShowDialog();
        }

        private void toolStripStatusLabel1_Click_1(object sender, EventArgs e)
        {
            if (null != uploadTask && !uploadTask.IsDisposed)
                uploadTask.ShowDialog();
        }

        private void cms_allRoles_Opening(object sender, CancelEventArgs e)
        {

        }

        private void cms_alitteRoles_Opening(object sender, CancelEventArgs e)
        {

        }

        private void cms_computerFile_Opening(object sender, CancelEventArgs e)
        {

        }

        /// <summary>
        /// Role copy to people
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_roleMoveTo_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox14_Click(object sender, EventArgs e)
        {
            if (null != tvFileView.SelectedNode.Parent)
                tvFileView.SelectedNode = tvFileView.SelectedNode.Parent;
        }

        private void 上一级目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (null != tvFileView.SelectedNode.Parent)
                tvFileView.SelectedNode = tvFileView.SelectedNode.Parent;
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
           // e.Cancel = true;
            if (lvFileView.SelectedItems.Count != 0)
            {
                var selectItem = lvFileView.SelectedItems[0];
                var args = selectItem.Tag as FileResult;
                if (null == args)
                    lvFileView.ContextMenuStrip = cms_FolderRightMenu;
                else
                    lvFileView.ContextMenuStrip = cms_FileRightMenu;
            }
            else
                lvFileView.ContextMenuStrip = contextMenuStrip1;
            lvFileView.ContextMenuStrip.Show();
        }


        private void cms_FolderRightMenu_Opening(object sender, CancelEventArgs e)
        {
         //   e.Cancel = true;
            if (lvFileView.SelectedItems.Count == 0)
            {
                e.Cancel = true;
                //var selectItem = lvFileView.SelectedItems[0];
                //var args = selectItem.Tag as FileResult;
                //if (null == args)
                //    lvFileView.ContextMenuStrip = cms_FolderRightMenu;
                //else
                //    lvFileView.ContextMenuStrip = cms_FileRightMenu;
            }
            //else
            //    lvFileView.ContextMenuStrip = contextMenuStrip1;
            //lvFileView.ContextMenuStrip.Show();
        }

        private void cms_FileRightMenu_Opening(object sender, CancelEventArgs e)
        {
           // e.Cancel = true;
            if (lvFileView.SelectedItems.Count == 0)
            {
                e.Cancel = true;
            }
            //else
            //    lvFileView.ContextMenuStrip = contextMenuStrip1;
            //lvFileView.ContextMenuStrip.Show();
        }

        private void tsmi_DeleteFile_Click(object sender, EventArgs e)
        {
            var delItem = lvFileView.SelectedItems[0].Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFileMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var fileDeleteArgs = new FileDeleteArgs
                                     {
                                         FileSidk__BackingField =
                                             (lvFileView.SelectedItems[0].Tag as FileResult).FileSidk__BackingField,
                                         UserIdk__BackingField = userSession.UserIdk__BackingField
                                     };
            var backgroundWorkerDeleteFile = new BackgroundWorker();
            backgroundWorkerDeleteFile.DoWork += backgroundWorkerDeleteFile_DoWork;
            backgroundWorkerDeleteFile.RunWorkerCompleted += backgroundWorkerDeleteFile_RunWorkerCompleted;
            backgroundWorkerDeleteFile.RunWorkerAsync(fileDeleteArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.DeleteingFileStr, GlobalString.System_Config_String.MbxInfoStr)
                                       {
                                           BackColor = BackColor
                                       };
                _waitBeforeLogin.Hide();
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
            }
            _waitBeforeLogin.ShowDialog();
        }

        void backgroundWorkerDeleteFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _waitBeforeLogin.Close();
            var fileDeleteResult = e.Result as FileDeleteResult;
            if(null != e.Result)
            {
                if(fileDeleteResult.Resultk__BackingField)
                {
                    XtraMessageBox.Show(GlobalString.System_Config_String.DeleteFileStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    var folderResult = (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult;
                    UpdateListView(folderResult.FileSidk__BackingField);
                }
                else
                {
                    var errorMessage = string.Empty;
                    switch (fileDeleteResult.ResultExceptionk__BackingField)
                    {
                            case BaseExceptionEnum.DeleteFileNotFileException:
                            errorMessage = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                            case BaseExceptionEnum.DeleteFileException:
                            errorMessage = GlobalString.System_Exception_String.DeleteFileExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(errorMessage, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            //Invoke((EventHandler) delegate
            //                          {
                                          
            //                          });

        }

        void backgroundWorkerDeleteFile_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = fileService.DeleteFile(e.Argument as FileDeleteArgs);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.DeleteFileExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }

        private void tsmi_RenameFile_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var fileNameCollection = (from ListViewItem item in lvFileView.Items select item.Text).ToList();
            var currentFileName = lvFileView.SelectedItems[0].Text;
            var fileSid = (lvFileView.SelectedItems[0].Tag as FileResult).FileSidk__BackingField;
            fileNameCollection.Remove(currentFileName);
            var reNameForm = new ReNameFile(fileNameCollection, fileSid, currentFileName,
                                            currentFolder.FolderResult.FileSidk__BackingField, this);
            reNameForm.ShowDialog();
        }

        private void tsmi_RenameFolder_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var fileNameCollection = (from ListViewItem item in lvFileView.Items select item.Text).ToList();
            var currentFileName = lvFileView.SelectedItems[0].Text;
            var fileSid = (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.FileSidk__BackingField;
            fileNameCollection.Remove(currentFileName);
            var reNameFolderForm = new ReNameFolder(fileNameCollection, fileSid, currentFileName, this);
            reNameFolderForm.ShowDialog();
        }

        /// <summary>
        /// ListView ContextMenu Delete Folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_DeleteFolder_Click(object sender, EventArgs e)
        {
            var delItem = lvFileView.SelectedItems[0].Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFolderMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var folderDeleteArgs = new FolderDeleteArgs
                                       {
                                           FolderSidk__BackingField =
                                               (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.FileSidk__BackingField,
                                           UserIdk__BackingField = userSession.UserIdk__BackingField
                                       };
            var backgroundWokerDeleteFolder = new BackgroundWorker();
            backgroundWokerDeleteFolder.DoWork += backgroundWokerDeleteFolder_DoWork;
            backgroundWokerDeleteFolder.RunWorkerCompleted += backgroundWokerDeleteFolder_RunWorkerCompleted;
            backgroundWokerDeleteFolder.RunWorkerAsync(folderDeleteArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.DeleteingFolderStr, GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
                _waitBeforeLogin.ShowDialog();
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
            }
        }

        void backgroundWokerDeleteFolder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var folderDeleteResult = e.Result as FolderDeleteResult;
            if (null != e.Result)
            {
                if (folderDeleteResult.Resultk__BackingField)
                {
                    var parentId = (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.ParentIdk__BackingField;
                   // XtraMessageBox.Show(GlobalString.System_Config_String.DeleteFolderStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    var _userService = new UserService();
                    _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderStr;
                    var folderCollectionResult = _userService.SyncGetFolderService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                    _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr;
                    var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                    _waitBeforeLogin.Close();
                    InitData();
                    UpdateListView(parentId);
                }
                else
                {
                    _waitBeforeLogin.Close();
                    var errorMessage = string.Empty;
                    switch (folderDeleteResult.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.DeleteFileNotFileException:
                            errorMessage = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                        case BaseExceptionEnum.DeleteFolderException:
                            errorMessage = GlobalString.System_Exception_String.DeleteFolderExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(errorMessage, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
          //  Invoke((EventHandler)delegate
         //   {
            _waitBeforeLogin.Close();
         //   });
        }

        void backgroundWokerDeleteFolder_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = fileService.DeleteFolder(e.Argument as FolderDeleteArgs);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.DeleteFolderExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }

        private void pbBigIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.LargeIcon;
        }

        private void pbSmallIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.List;
        }

        private void pbListIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.Details;
        }

        private void tsmi_AuthCopyTo_Click(object sender, EventArgs e)
        {

        }

        private void ServerFiles_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((ModifierKeys & Keys.Control) != 0 && e.KeyChar == 70)
            {
                var fs = new FileSerch(this);
                fs.ShowDialog();
            }
            if ((ModifierKeys & Keys.Control) == 0 || e.KeyChar != 117) return;
            if (pbSubmitFalse.Cursor == Cursors.No && pbEditTrue.Cursor == Cursors.No && pbDeleteFalse.Cursor == Cursors.No
                && pbCreateTrue.Cursor == Cursors.No)
                return;
            var dlg = new OpenFileDialog { Multiselect = true, RestoreDirectory = true }; //创建一个OpenFileDialog  
            if (dlg.ShowDialog() != DialogResult.OK) return;
            if (dlg.FileNames == null || !dlg.FileNames.Any()) return;
            var message = string.Format(GlobalString.System_Config_String.UploadFileMessageBox,
                                        dlg.FileNames.Count());
            XtraMessageBox.AllowCustomLookAndFeel = true;
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            uploadTask = new UploadTask(dlg.FileNames, nodeArgs.FolderResult, tsslUploadTask, this);
            uploadTask.ShowDialog();
        }

        private void tsmi_FolderCopyTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as NodeArgs;
            if(null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FolderCopy, obj.FolderResult.FileSidk__BackingField);
            folderCopy.ShowDialog();
        }

        private void tsmi_FolderCutTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FolderCut, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_FileCopyTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FileCopy, obj.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_FileCutTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null == obj) return;
            var folderCopy = new FileCopyTo(FolderFileDoEnum.FileCut, obj.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        void folderCopy_Closed(object sender, EventArgs e)
        {
            var folderCopy = sender as FileCopyTo;
            if(null == folderCopy || folderCopy.CopyToFolderSid.Count <= 0) return;
            switch (folderCopy._folderFileDoEnum)
            {
                    case FolderFileDoEnum.FolderCut:
                    FolderCut(folderCopy.CutFolderSid, folderCopy._folderOrfileSid);
                    break;
                    case FolderFileDoEnum.FolderCopy:
                    FolderCopy(folderCopy.CopyToFolderSid, folderCopy._folderOrfileSid);
                    break;
                    case FolderFileDoEnum.FileCut:
                    FileCut(folderCopy.CutFolderSid, folderCopy._folderOrfileSid);
                    break;
                    case FolderFileDoEnum.FileCopy:
                    FileCopy(folderCopy.CopyToFolderSid, folderCopy._folderOrfileSid);
                    break;
            }
        }

        private void FolderCopy(List<string> targetCollection,string folderSid)
        {
            var folderCopyBackgroundWorker = new BackgroundWorker();
            folderCopyBackgroundWorker.DoWork += folderCopyBackgroundWoker_DoWork;
            var folderCopyArgs = new FolderCopyToArgs
                                     {
                                         FolderSidk__BackingField = folderSid,
                                         TargetFolderSidk__BackingField = targetCollection.ToArray(),
                                         UserIdk__BackingField = userSession.UserIdk__BackingField
                                     };
            folderCopyBackgroundWorker.RunWorkerAsync(folderCopyArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FolderCopyStr,
                                                      GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
            }
            _waitBeforeLogin.ShowDialog();
        }

        void folderCopyBackgroundWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if(!IsHandleCreated)
                    CreateHandle();
                var folderCopyArgs = e.Argument as FolderCopyToArgs;
                var result = fileService.CopyFolderTo(folderCopyArgs);
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                if(result.Resultk__BackingField)
                {
                    Invoke((EventHandler) delegate
                                              {
                                                  var _userService = new UserService();
                                                  _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderStr;
                                                  var folderCollectionResult = _userService.SyncGetFolderService();
                                                  CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                                                  _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr;
                                                  var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                                                  CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                                                  _waitBeforeLogin.Close();
                                                  InitData();
                                                  UpdateListView(folderCopyArgs.FolderSidk__BackingField);
                                              });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                            case BaseExceptionEnum.CopyFolderException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("folderCopyBackgroundWoker_DoWork has problem", ex);
                XtraMessageBox.Show("复制文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void FolderCut(string targetFolderSid,string folderSid)
        {
            var folderCutBackgroundWorker = new BackgroundWorker();
            folderCutBackgroundWorker.DoWork += folderCutBackgroundWoker_DoWork;
            var folderCutArgs = new FolderCutToArgs
                                    {
                                        FolderSidk__BackingField = folderSid,
                                        TargetFolderSidk__BackingField = targetFolderSid,
                                        UserIdk__BackingField = userSession.UserIdk__BackingField
                                    };
            folderCutBackgroundWorker.RunWorkerAsync(folderCutArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FolderCutStr,
                                                      GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
            }
            _waitBeforeLogin.ShowDialog();
        }

        void folderCutBackgroundWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                var folderCutArgs = e.Argument as FolderCutToArgs;
                var result = fileService.CutFolderTo(folderCutArgs);
                if(result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        var _userService = new UserService();
                        _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderStr;
                        var folderCollectionResult = _userService.SyncGetFolderService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                        _waitBeforeLogin.Caption = GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr;
                        var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                        _waitBeforeLogin.Close();
                        InitData();
                        UpdateListView(folderCutArgs.FolderSidk__BackingField);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CutFolderException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("folderCutBackgroundWoker_DoWork has problem", ex);
                XtraMessageBox.Show("剪切文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void FileCopy(List<string> targetCollection,string folderSid)
        {
            var fileCopyBackgroundWorker = new BackgroundWorker();
            fileCopyBackgroundWorker.DoWork += fileCopyBackgroundWorker_DoWork;
            var fileCopyArgs = new FileCopyToArgs
                                   {
                                       FileSidk__BackingField = folderSid,
                                       TargetFolderSidk__BackingField = targetCollection.ToArray(),
                                       UserIdk__BackingField = userSession.UserIdk__BackingField
                                   };
            fileCopyBackgroundWorker.RunWorkerAsync(fileCopyArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FileCopyStr,
                                                      GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
            }
            _waitBeforeLogin.ShowDialog();
        }

        void fileCopyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                var fileCopyArgs = e.Argument as FileCopyToArgs;
                var result = fileService.CopyFileTo(fileCopyArgs);
                if(result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        UpdateListView(tvFileView.SelectedNode.Name);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CopyFileException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }

            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("fileCopyBackgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("复制文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }
        
        private void FileCut(string targetFolderSid,string folderSid )
        {
            var fileCutBackgroundWorker = new BackgroundWorker();
            fileCutBackgroundWorker.DoWork += fileCutBackgroundWorker_DoWork;
            var fileCutArgs = new FileCutToArgs
                                  {
                                      FileSidk__BackingField = folderSid,
                                      TargetFolderSidk__BackingField = targetFolderSid,
                                      UserIdk__BackingField = userSession.UserIdk__BackingField
                                  };
            fileCutBackgroundWorker.RunWorkerAsync(fileCutArgs);
            lock (_lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FileCutStr,
                                                      GlobalString.System_Config_String.MbxInfoStr)
                {
                    BackColor = BackColor
                };
                _waitBeforeLogin.Hide();
            }
            _waitBeforeLogin.ShowDialog();
        }

        void fileCutBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                var fileCutArgs = e.Argument as FileCutToArgs;
                var result = fileService.CutFileTo(fileCutArgs);
                if(result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        UpdateListView(tvFileView.SelectedNode.Name);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CutFileException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("fileCutBackgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("剪切文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

    }
}
